package ay.shadow.openfein.config;

import ay.shadow.openfein.client.CustomBlockingLoadBalancerClient;
import ay.shadow.openfein.client.LokiJackson2HttpMessageConverter;
import feign.codec.Decoder;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.cloud.client.loadbalancer.LoadBalancerProperties;
import org.springframework.cloud.loadbalancer.support.LoadBalancerClientFactory;
import org.springframework.cloud.openfeign.support.SpringDecoder;
import org.springframework.context.annotation.Bean;

/**
 * OpenFeign自动装配配置
 * @author shadow
 */
public class FeinConfig {
    
    @Autowired
    LoadBalancerClientFactory loadBalancerClientFactory;

    @Autowired
    LoadBalancerProperties properties;

    /**
     * 解决 http调用错误
     * block()/blockFirst()/blockLast() are blocking, which is not supported in thread reactor-http-nio-2
     */
    @Bean
    public LoadBalancerClient blockingLoadBalancerClient() {
        return new CustomBlockingLoadBalancerClient(loadBalancerClientFactory, properties);
    }

    /**
     * 解决返回对应错误 没有正确解析对应返回信息
     * Could not extract response: no suitable HttpMessageConverter found for response type [class java.lang.Object] and content type [text/plain;charset=UTF-8]
     */
    @Bean
    public Decoder feignDecoder() {
        LokiJackson2HttpMessageConverter converter = new LokiJackson2HttpMessageConverter();
        ObjectFactory<HttpMessageConverters> objectFactory = () -> new HttpMessageConverters(converter);
        return new SpringDecoder(objectFactory);
    }
}
